package cn.edu.ctbu.kcsj.service.impl;

import cn.edu.ctbu.kcsj.constain.REnum;
import cn.edu.ctbu.kcsj.domain.Student;
import cn.edu.ctbu.kcsj.exception.RException;
import cn.edu.ctbu.kcsj.repository.StudentRepository;
import cn.edu.ctbu.kcsj.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentImplService implements StudentService {
    @Autowired
    private StudentRepository studentRepository;
    public  List<Student> findAll() {
        return studentRepository.findAll();
    }
    /**
     * 只分页的查询
     * @param pageable
     * @return
     */
    public Page<Student> findAll(Pageable pageable){
        return studentRepository.findAll(pageable);
    }
    /**
     * 分页，带过滤的查询
     * @param student
     * @param pageable
     * @return
     */
    public Page<Student> findAll(Example<Student> student, Pageable pageable){
        return studentRepository.findAll(student,pageable);
    }
    /**
     * 按名字进行查询，like
     *
     * @param sname 字符串
     * @return
     */
    public List<Student> findBySnameLike(String sname) {

        return studentRepository.findBySnameLike(sname);
    }
    /**
     * 按学号和密码查询
     *
     * @param sno
     * @param password
     * @return
     */
    public List<Student> findBySnoAndPassword(Integer sno, String password) {
        return studentRepository.findBySnoAndPassword(sno, password);
    }
    public Student insert(Student student){

        return studentRepository.save(student);
    }
    public Student update(Student student){
        return studentRepository.save(student);
    }
    public void delete(Student student){

        studentRepository.delete(student);
    }
    public void delete(Integer sno){
        Student student=new Student();
        student.setSno(sno);
        studentRepository.delete(student);
    }
    public Student getBySno(Integer sno){
        Student student=studentRepository.findById(sno).orElse(null);
        return student;
    }
    @Override
    public Student validateSnoAndPassword(Integer sno,String password) throws Exception{
        List<Student> students=studentRepository.findBySno(sno);
        if (students.size()>0){
            Student student=students.get(0);
            if (student.getPassword().equals(password)){
                return student;
            }
            else {
                throw new RException(REnum.LOGIN_ERR);}

        }else {
            throw new RException(REnum.LOGIN_ERR);
        }
    }
}
